import requests
import asyncio
import aiohttp
import aiofiles
import re
import subprocess
import os

url = "https://ali-safety-video.acfun.cn/mediacloud/acfun/acfun_video/e8ddcc5f8fdca899-0218cca9341e48219ccf9354424baf32-hls_1080p_h264_60_1.m3u8?pkey=ABCDhc5H-fFmvuw-f-LeU7WCEe8OxIaO87ODw2y9iauro3Q1dDNhaPkabbmezKFtIgTtiady6X_8TS2KWlvFrRYOYu8byeMHgfgX9oP_qzZINvLsSw7i4yDxKd6jS6nN473W8f3jF0Xg651Jo9o9qOuDdFyaiFm6_L8_I9RYSE9r7e54h8F0X6DzJCqw6Wz8D1En5vLr5rHPO80H9Y3hciGPR7Wvz51uyihsHwAI6aLNMfUEvZBHfY2Bye0AV_7FJBE&safety_id=AAIszakpHtramSR5GHo65R5H"

# rsp = requests.get(url)
# with open('ac_m3u8.txt', mode='wb') as f:
#     f.write(rsp.content)
#
domain = "https://ali-safety-video.acfun.cn/mediacloud/acfun/acfun_video/hls/"


async def download_video(url, name):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as rsp:
            async with aiofiles.open(f'ac_rsc/{name}', 'wb') as ff:
                await ff.write(await rsp.content.read())
                print(f'{name}已下载')


async def main():
    with open('ac_m3u8.txt', mode='r') as f:
        tasks = []
        for line in f:
            if line.startswith('#'):
                continue
            line.strip()
            id = re.findall(r'(\d+).ts', line)[0]
            line = domain + line
            task = asyncio.create_task(download_video(line, f'{id}.ts'))
            tasks.append(task)
        await asyncio.wait(tasks)


def merge_video(adr_file_fullpath, output_file_fullpath):
    cm = r'ffmpeg -y -f concat -safe 0 -i ' + adr_file_fullpath + ' -c copy ' + output_file_fullpath
    os.system(cm)


if __name__ == '__main__':
    # asyncio.run(main())
    merge_video(r'D:\Code\Python_code\python_learning\crawlers\Cases\adr_file.txt', r'D:\Code\Python_code\python_learning\crawlers\Cases\test.mp4')
